//
//  UILabel+Text.m
//  StaffTax
//
//  Created by 侯伟 on 2020/6/2.
//  Copyright © 2020 侯伟. All rights reserved.
//

#import "UILabel+Text.h"
#import <CoreText/CoreText.h>
@implementation UILabel (Text)

+(NSAttributedString *)theRichText:(NSString *)string theRange:(NSUInteger)theRange changeRange:(NSInteger)changeRange color:(UIColor *)color{
    
    NSMutableAttributedString *noteStr = [[NSMutableAttributedString alloc] initWithString:string];
    NSRange redRange = NSMakeRange(theRange,changeRange);
    [noteStr addAttribute:NSForegroundColorAttributeName value:color range:redRange];
    return noteStr;
}

- (NSInteger)setText:(NSString*)text breakIndex:(NSInteger)breakIndex{
    
    return [self setText:text breakIndex:breakIndex lineWidth:CGRectGetWidth(self.frame)];
}

- (NSInteger)setText:(NSString*)text breakIndex:(NSInteger)breakIndex lineWidth:(CGFloat)lineWidth{
    
    if(!text.length || breakIndex < 1){
        self.text = text;
        return 1;
    }
    NSArray* lines = [self getTextLinesArray:text lineWidth:lineWidth];
    
    NSMutableString* str = [NSMutableString new];
    [lines enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if(idx < breakIndex){
            [str appendString:obj];
        }
    }];
    if(lines.count > breakIndex && str.length > 3){
        self.text = [str stringByReplacingCharactersInRange:NSMakeRange(str.length-3, 3) withString:@"..."];
    }else{
        self.text = str;
    }
    
    return lines.count;
}


- (NSArray*)getTextLinesArray:(NSString*)text{
    return [self getTextLinesArray:text lineWidth:CGRectGetWidth(self.frame)];
}


- (NSArray*)getTextLinesArray:(NSString*)text lineWidth:(CGFloat)lineWidth{
    
    NSAttributedString* attStr = [[NSAttributedString alloc] initWithString:text attributes:@{NSFontAttributeName:self.font}];
    CTFramesetterRef frameSetter = CTFramesetterCreateWithAttributedString((CFAttributedStringRef)attStr);
    CGMutablePathRef path = CGPathCreateMutable();
    CGPathAddRect(path, NULL, CGRectMake(0, 0, lineWidth, CGFLOAT_MAX));
    
    CTFrameRef frame = CTFramesetterCreateFrame(frameSetter, CFRangeMake(0, 0), path, NULL);
    NSArray* lines = (NSArray*)CTFrameGetLines(frame);
    NSMutableArray* lineArr = [NSMutableArray array];
    for (id line in lines) {
        CTLineRef l = (__bridge CTLineRef)line;
        CFRange range = CTLineGetStringRange(l);
        NSString* rangeStr = [text substringWithRange:NSMakeRange(range.location, range.length)];
        [lineArr addObject:rangeStr];
    }
    return lineArr;
}

- (CGFloat)stringHeight:(NSString*)string maxW:(CGFloat)maxW{
    CGFloat textW = [string boundingRectWithSize:CGSizeMake(maxW, MAXFLOAT) options: NSStringDrawingUsesFontLeading | NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:self.font} context:NULL].size.width;
    return textW;
}

@end
